//
//  UserManager.m
//  HYSmileiOS
//
//  Created by alekye on 16/5/29.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "UserManager.h"
#import "HttpProvider.h"
#import "HYNotifications.h"
#import "UserDataManager.h"

#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"

#define kAppKeySina         @"1826833466"
#define kAppSecretSina      @"ba381e1c7edfa5cd119366a3b898cd59"
#define kRedirectURISina    @"https://api.weibo.com/oauth2/default.html"

@interface UserManager () {
    
}

// 当前登录用户信息
@property (strong, nonatomic) UserInfoDetail *mCurrentUser;

@end

@implementation UserManager

/**
 *  用户管理
 *
 *  @return 单实例
 */
+ (instancetype)sharedInstance {
    static UserManager *userInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userInstance = [[self alloc] init];
    });
    return userInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self readCurrentUserFromLocal];
        [self _initSDKs];
    }
    return self;
}

#pragma mark -- init sdks
- (void)_initSDKs {
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"iosv1101"
          activePlatforms:@[@(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ)]
                 onImport:^(SSDKPlatformType platformType) {
         switch (platformType) {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
         switch (platformType) {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:kAppKeySina
                                           appSecret:kAppSecretSina
                                         redirectUri:kRedirectURISina
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx4868b35061f87885"
                                       appSecret:@"64020361b8ec4c99936c0e3999a9f249"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"100371282"
                                      appKey:@"aed9b0303e3ed1e27bae87c33761161d"
                                    authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
}

/**
 *  获取用户是否登录的状态
 *
 *  @return 是否登录
 */
- (BOOL)isUserLogin {
    BOOL bRet = NO;
    
    if (self.mCurrentUser && self.mCurrentUser.from != SSDKPlatformTypeUnknown) {
        bRet = YES;
    }
    
    return bRet;
}

/**
 *  获取当前登录用户
 *
 *  @return 用户信息
 */
- (UserInfoDetail*)getCurrentUser {
    UserInfoDetail *user = self.mCurrentUser;
    return user;
}

/**
 *  登录成功
 */
- (void)_onLoginSuccess {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter postNotificationName:USER_LOGIN_SUCCESS object:nil];
}

/**
 *  登录失败
 */
- (void)_onLoginFailure:(NSError*)error {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter postNotificationName:USER_LOGIN_FAILURE object:nil];
}

/**
 *  退出账号成功
 */
- (void)_onLogoutSuccess {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter postNotificationName:USER_LOGOUT_DONE object:nil];
}

/**
 *  登录App服务器，绑定用户信息
 *
 *  @param user 第三方平台用户信息
 */
- (void)_getUserDetailInfoFromMyServer:(SSDKUser*)user {
    WS(ws);
    UserInfoBrief *brief = [UserInfoBrief new];
    brief.openid = user.uid;
    brief.nickname = user.nickname;
    brief.headimgurl = user.icon;
    brief.from = user.platformType;
    [HttpProvider getUserDetailInfo:brief success:^(UserInfoDetail *detail) {
        NSLog(@"获取微博用户详细信息 OK");
        detail.uid = 109527;
        self.mCurrentUser = detail;
        [self saveCurrentUserToLocal];
        [ws _onLoginSuccess];
    } failure:^(NSError *error) {
        NSLog(@"获取微博用户详细信息 Error");
        [ws _onLoginFailure:error];
    }];
}

- (void)login:(SSDKPlatformType)platformType {
    //例如 微博 的登录
    [ShareSDK getUserInfo:platformType
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
         if (state == SSDKResponseStateSuccess) {
             [self _getUserDetailInfoFromMyServer:user];
         } else {
             [self _onLoginFailure:error];
         }
     }];
}

/**
 *  退出当前账号
 */
- (void)userLogout {
    if ([self isUserLogin]) {
        self.mCurrentUser = [UserInfoDetail new];
        [self saveCurrentUserToLocal];
        [self _onLogoutSuccess];
    }
}

// 处理系统启动时，传递的信息
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    BOOL bRet = NO;
    
    return bRet;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    BOOL bRet = NO;
    
    return bRet;
}

/**
 *  保存当前用户信息
 */
- (void)saveCurrentUserToLocal {
    [[UserDataManager sharedInstance] saveUserDataToLocal:self.mCurrentUser];
}
/**
 *  读取本地用户信息
 */
- (void)readCurrentUserFromLocal {
    UserInfoDetail *userData = [[UserDataManager sharedInstance] readUserDataFromLocal];
    if (userData == nil) {
        userData = [UserInfoDetail new];
    }

    self.mCurrentUser = userData;
}

@end
